﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using BestHTTP;
using System;

public class ModuleDownloadSystem : MonoSingleton<ModuleDownloadSystem> {
    

    private const int UNZIP_SIZE = 524228;

    private int curId;

	private float mDownloadProgress = 0f;
    private float mUnzipProgress = 0;

	private string UpdatePath {
		get {
			string updatePath = FileTools.CombinePath (Application.persistentDataPath, "ModuleUpdate");
			if (!Directory.Exists (updatePath)) {
				Directory.CreateDirectory (updatePath);
			}
			return updatePath;
		}
	}

	protected override void Init ()
	{
		base.Init ();
	}

    public float Progress
    {
        get
        {
            return (mDownloadProgress + mUnzipProgress) / 2f;
        }
    }

	public void StartDownload(int id, string name, int version) {
        Debug.Log("创建Task！ ----  id: " + id + "  name: " + name + "   version: " + version);
        curId = id;
        mDownloadProgress = 0f;
        mUnzipProgress = 0f;
        DownloadTask task = new DownloadTask ();
		task.URL = AppConfig.ServerURL + "/" + name + "/" + version + "/" + name + ".zip";
        Debug.Log(task.URL);
		task.SavePath = FileTools.CombinePath(UpdatePath, name + ".zip");
        if (FileTools.IsFileExist(task.SavePath)) {
			FileTools.DeleteFile (task.SavePath);
		}
		task.OnProgress = new DownloadTask.OnProgressDelegate (delegate(long totalSize, long nowSize) {
			task.DownloadedSize = nowSize;
			this.mDownloadProgress = ((float)nowSize) / totalSize;
            EventBus.Instance.BroadCastEvent<int, float>(EventID.MODULE_PROGRESS_CHANGE, curId, Progress);
            //UpdateUIProgress("正在下载", this.mProgress);
        });

		task.OnSuccess = delegate() {
			task.DownloadedSize = task.Size;
			Debug.LogError ("下载完成 " + name);
			StartCoroutine(StartUnzip(UpdatePath, name));
		};
		task.OnError = delegate(string errorString) {
			Debug.LogError(errorString);
            EventBus.Instance.BroadCastEvent<int>(EventID.MODULE_DOWNLOAD_ERROR, curId);
		};
		DownloadManager.Instance.AddTask (task, true);
	}

	public void Unzip(string path, string name) {
		StartCoroutine(StartUnzip(path, name));
	}

	IEnumerator StartUnzip(string path, string name) {
        string fromPath = FileTools.CombinePath(path, name + ".zip");
        long allS = 0;
		using (ZipInputStream s = new ZipInputStream (File.OpenRead (fromPath))) {
			ZipEntry theEntry;
			while ((theEntry = s.GetNextEntry ()) != null) {
				allS += s.Length;
			}
		}

		using (ZipInputStream s = new ZipInputStream(File.OpenRead(fromPath))) {
			ZipEntry theEntry;
			long allSize = 0;

			while ((theEntry = s.GetNextEntry()) != null) {
				string fileName = Path.GetFileName(theEntry.Name);
				if (!string.IsNullOrEmpty(fileName)) {
					string toFilePath = ResourceManager.PersistentAssetPath + "/" + fileName;
					if (File.Exists(toFilePath)) {
						File.Delete(toFilePath);
					}
					using (FileStream streamWriter = File.Create(toFilePath)) {
						int size = UNZIP_SIZE;
						byte[] data = new byte[UNZIP_SIZE];
						while (true) {
							size = s.Read(data, 0, data.Length);
							if (size > 0) {
								streamWriter.Write(data, 0, size);
							} else {
								break;
							}
							allSize += size;
							this.mUnzipProgress = ((float)allSize) / allS;
                            EventBus.Instance.BroadCastEvent<int, float>(EventID.MODULE_PROGRESS_CHANGE, curId, Progress);
                            //UpdateUIProgress("正在减压", this.mProgress);
                            yield return null;
						}
					}
				}
			}
		}
		yield return null;
        FileTools.ClearDirectory(UpdatePath);
        EventBus.Instance.BroadCastEvent<int, long>(EventID.MODULE_UNZIP_DONE, curId, allS);
		Debug.LogError ("解压完成 " + name);
	}

	public void CopyZip(string fromPath, string name) {
		StartCoroutine (AndroidCopy(fromPath, name));
	}

	IEnumerator AndroidCopy(string fromPath, string name) {
		fromPath = FileTools.CombinePath (fromPath, name+".zip");

		string toPath = FileTools.CombinePath (UpdatePath, name+".zip");;

		UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(fromPath);
		yield return www.SendWebRequest();
		if (File.Exists(toPath))  
		{  
			File.Delete(toPath);  
		}  
		FileStream fsDes = File.Create(toPath);  
		fsDes.Write(www.downloadHandler.data, 0, www.downloadHandler.data.Length);
		fsDes.Flush();  
		fsDes.Close();  
		Unzip (toPath, name);
	}

    private void Update()
    {
        
    }

    private void UpdateUIProgress(string count, float progress) {
		Debug.Log (count + progress);
	}

	public void CheckUpdate(int id, string name, int codeV, Action needAction) {
		HTTPRequest resourceRequest = new HTTPRequest(new System.Uri(AppConfig.ServerURL + "/" + name + "/" + codeV + "/" + name+ModuleAssetManager.ResName), HTTPMethods.Get, (req, resp) => {
			if (req.State == HTTPRequestStates.Finished && resp != null) {
				string text = resp.DataAsText.Trim();
				//Debug.Log(text);
				string info = File.ReadAllText (FileTools.CombinePath(ResourceManager.PersistentAssetPath, name + ModuleAssetManager.ResName));
				//Debug.Log(info);
				ResourceInfo resInfo = JsonUtility.FromJson<ResourceInfo> (info);
				ResourceInfo newInfo = JsonUtility.FromJson<ResourceInfo>(text);

				if (newInfo.ResVersion > resInfo.ResVersion) {
					Debug.Log(name + "需要更新");
                    needAction();
				}
                else
                {
                    Debug.Log(name + "不需要更新");
                }

			} else {
				Debug.LogError("获取资源更新文件出错！");
			}
		});
		resourceRequest.DisableCache = true;
		resourceRequest.Send ();
	}
}
